package controllers

import (
	"fmt"
	"log"
	m "xwaf_admin/models"

	"strconv"
	//"strings"

	"github.com/tidwall/gjson"
	//"golang.org/x/text/encoding/simplifiedchinese"
)

type WafappController struct {
	CommonController
}

//列表
func (this *WafappController) List() {
	// userinfo := this.GetSession("userinfo")
	// if userinfo == nil {
	// 	//this.Ctx.Redirect(302, "/public/Ulogin")
	// 	this.Data["json"] = &map[string]interface{}{"code": 201, "msg": "登录过期"}
	// 	this.ServeJSON()
	// 	return
	// }
	//fmt.Println(string(this.Ctx.Input.RequestBody))
	if this.Ctx.Request.Method == "POST" {
		gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
		// for kk, vv := range gp.Map() {
		// 	log.Println(kk, vv.String())
		// }
		datas, count := m.GetXf_appListV2(gp.Map())
		this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
		this.ServeJSON()
		//this.Ctx.WriteString(`{"code":-1,"msg":"test"}`)
		return
	} else {
		page, _ := this.GetInt64("page")
		page_size, _ := this.GetInt64("limit")
		id, _ := this.GetInt64("id")
		// sort := this.GetString("sort")
		// order := this.GetString("order")
		// if len(order) > 0 {
		// 	if order == "desc" {
		// 		sort = "-" + sort
		// 	}
		// } else {
		// 	sort = "id"
		// }
		datas, count := m.GetXf_appList(page, page_size, id)
		this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
		this.ServeJSON()
		return
	}
}

//添加
func (this *WafappController) Add() {
	// userinfo := this.GetSession("userinfo")
	// if userinfo == nil {
	// 	//this.Ctx.Redirect(302, "/public/Ulogin")
	// 	this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "登录过期"}
	// 	this.ServeJSON()
	// 	return
	// }
	u := m.Xf_app{}
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
	if gp.Get("appname").Exists() {
		u.Appname = gp.Get("appname").String()
		u.Jrtype = gp.Get("jrtype").String()
		u.Clusterid = gp.Get("clusterid").String()
		u.Deployment = gp.Get("deployment").String()
		u.Namespace = gp.Get("namespace").String()
		u.Serverip = gp.Get("serverip").String()
		u.Remarks = gp.Get("remarks").String()
	} else {
		if err := this.ParseForm(&u); err != nil {
			//			this.Rsp(false, err.Error())
			log.Printf("[ERROR] AddWafapp Error:%s\n", err)
			this.Ctx.WriteString(`{"code":-1,"msg":"ParseFormError"}`)
			return
		}
	}

	id, err := m.AddXf_app(&u)
	if err == nil && id > 0 {
		log.Printf("[INFO] AddWafapp success")

		//创建waf规则、创建waf配置、reqlimit配置
		num, err1 := m.InsertWafRule(u.Appname)
		if err1 == nil && num > 0 {
			num2, err2 := m.InsertConfig(u.Appname)
			if err2 == nil && num2 > 0 {
				this.Ctx.WriteString(`{"code":0,"msg":"addSuccess"}`)
			} else {
				this.Ctx.WriteString(`{"code":-1,"msg":"AddConfigError"}`)
			}
		} else {
			this.Ctx.WriteString(`{"code":-1,"msg":"AddWafRuleError"}`)
		}
	} else {
		log.Printf("[ERROR] AddSlb Error:%s\n", err)
		this.Ctx.WriteString(`{"code":-1,"msg":"AddWafappError"}`)
		return
	}

}

func (this *WafappController) Update() {
	// userinfo := this.GetSession("userinfo")
	// if userinfo == nil {
	// 	//this.Ctx.Redirect(302, "/public/Ulogin")
	// 	this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "登录过期"}
	// 	this.ServeJSON()
	// 	return
	// }
	u := m.Xf_app{}
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
	if gp.Get("appname").Exists() {
		u.Id = gp.Get("id").Int()
		u.Appname = gp.Get("appname").String()
		u.Jrtype = gp.Get("jrtype").String()
		u.Clusterid = gp.Get("clusterid").String()
		u.Deployment = gp.Get("deployment").String()
		u.Namespace = gp.Get("namespace").String()
		u.Serverip = gp.Get("serverip").String()
		u.Remarks = gp.Get("remarks").String()
	} else {
		if err := this.ParseForm(&u); err != nil {
			//			this.Rsp(false, err.Error())
			log.Printf("[ERROR] UpdateWafapp Error:%s\n", err)
			this.Ctx.WriteString(`{"code":-1,"msg":"ParseFormError"}`)
			return
		}
	}

	id, err := m.UpdateXf_app(&u)
	if err == nil && id > 0 {
		log.Printf("[INFO] UpdateWafapp success")
		this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		return
	} else {
		log.Printf("[ERROR] UpdateWafapp Error:%s\n", err)
		this.Ctx.WriteString(`{"code":-1,"msg":"UpdateWafappError"}`)
		return
	}
}

//删除
func (this *WafappController) Del() {
	// userinfo := this.GetSession("userinfo")
	// if userinfo == nil {
	// 	//this.Ctx.Redirect(302, "/public/Ulogin")
	// 	this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "登录过期"}
	// 	this.ServeJSON()
	// 	return
	// }
	var id string
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
	if gp.Get("id").Exists() {
		id = gp.Get("id").String()
	} else {
		id = this.GetString("id")
	}
	idInt, _ := strconv.ParseInt(id, 10, 64)
	num, err := m.DelXfappById(idInt)
	if err == nil && num > 0 {
		log.Printf("[INFO] Del success")
		this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		return
	} else {
		log.Printf("[ERROR] Del Error:%s\n", err.Error())
		this.Ctx.WriteString(`{"code":-1,"msg":"DelError"}`)
		return
	}
}

func (this *WafappController) Edit() {
	id := this.GetString("id")
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("name").Exists() {
		id = gp.Get("id").String()
		name := gp.Get("name").String()
		value := gp.Get("value").String()
		_, err := m.EditApp(id, name, value)
		if err == nil {
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] update app Fail:%s\n", err)
			this.Ctx.WriteString(fmt.Sprintf(`{"code":-1,"msg":"%s"}`, err.Error()))
		}
	} else {
		this.Ctx.WriteString(`{"code":-1,"msg":"bodyParseFail"}`)
	}
}

// //删除
// func (this *WafappController) ApplyConfig() {

// 	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
// 	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

// 	appname := this.GetString("appname")
// 	_ = m.ApplyConfig(appname)
// 	this.Ctx.WriteString(`{"code":0,"msg":"ok"}`)
// }
